<template>
  <a-card>
    <template #title>
      <BackButton />
      <a-input
        v-model:value="formModel.title"
        style="width: 50%; margin-left: 10px"
        placeholder="请输入一个标题"
      />
      <a-button type="primary" style="margin-left: 10px" @click.prevent="onSubmit"
        >保存</a-button
      >
    </template>
    <Markdown :md="formModel.md" @md-editor="getMdEditor" />
  </a-card>
</template>
<script>
import { onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { articleCfg, addArticleCfg, updateArticleCfg } from "@/api/article.conf";
import { useService } from "@/utils/request";
import { message } from "ant-design-vue";
export default {
  setup() {
    const route = useRoute();
    const router = useRouter();
    const articleRequest = useService(articleCfg);
    const addArticleRequest = useService(addArticleCfg);
    const updateArticleRequest = useService(updateArticleCfg);
    //md编辑器对象
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    let editor = null;

    const formModel = reactive({
      title: "",
      md: "",
    });

    //编辑ID
    let editArticleId = null;
    onMounted(() => {
      const { id } = route.params;

      if (id) {
        editArticleId = id;
        articleRequest
          .setEndPath(id)
          .reload()
          .then((response) => {
            const res = response.data || [];
            formModel.title = (res[0] || {}).title;
            formModel.md = (res[0] || {}).md;
          });
      } else {
        formModel.name = "";
      }
    });

    const onSubmit = () => {
      const html = editor.getHTML();
      const md = editor.getValue();
      const data = {
        title: formModel.title,
        html,
        md,
      };

      if (!data.title) {
        message.error("请输入一个合适的标题");
        return;
      }

      if (data.md.length < 10) {
        message.error("正文内容太少了!!!");
        return;
      }
      //修改一个内容
      if (editArticleId) {
        updateArticleRequest.setEndPath(editArticleId).setData(data).reload(true);
        return;
      }
      //新增内容
      addArticleRequest.setData(data).reload(true, (response) => {
        response.then((res) => {
          const data = res.data;
          const article = data[0] || {};
          editArticleId = article.id;
          router.push({
            name: "editArticle",
            params: {
              id: editArticleId,
            },
          });
        });
      });
    };

    //获取编辑器对象
    function getMdEditor(vditor) {
      editor = vditor;
    }

    return {
      onSubmit,
      formModel,
      getMdEditor,
    };
  },
};
</script>
